package com.fly.hello.web.async;

import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fly.hello.service.AsynService;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Api(tags = "注解异步方法，支持http接口和方法")
@RestController
@RequestMapping("/boot/async")
public class AsynBootController
{
    @Autowired
    AsynService asynService;
    
    /**
     * 使用@Async处理异步任务时没有异步回调响应客户端的流程<BR>
     * task1并不返回字符串"OK"，控制器立即会给客户端空响应，但是控制器方法依旧执行
     */
    @Async
    @GetMapping("task1")
    public String task1()
        throws InterruptedException
    {
        log.info("id: {}", RandomStringUtils.randomAlphabetic(10));
        for (int i = 0; i < 10; i++)
        {
            log.info("i = {}", i);
            TimeUnit.MILLISECONDS.sleep(500);
        }
        return "OK";
    }
    
    /**
     * 将@Async加在Service上或是 Service 的方法上, 控制器不再等待Service方法执行完毕就响应客户端
     * 
     * @return
     */
    @GetMapping("task2")
    public String task2()
    {
        String id = RandomStringUtils.randomAlphabetic(10);
        log.info("id: {}", id);
        asynService.test(id);
        return "OK";
    }
    
    @GetMapping("task3")
    public String task3()
    {
        asynService.test("key", RandomStringUtils.randomAlphabetic(10));
        return "OK";
    }
}
